/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package agents;

import ai1.Enviroment;

/**
 *
 * @author orcas
 */
public class GreedyAgent extends Agent {

    int targetR, targetC;
    boolean hasTarget;

    public GreedyAgent(String name, int row, int col, String orientation) {
        super(name, row, col, orientation);
        hasTarget = false;
    }

    public String getMove(Enviroment env) {
        String move = null;
        if(targetR==getRow() && targetC==getCol())
            hasTarget=false;
        if (!hasTarget) {
            findTarget(env);
        }
        if (getOrientation().equals("North")) {
            if (targetR < getRow() && env.isCellFree(getRow() -1, getCol() )) {
                move = "FWD"; //this is a good direction
            } else if (targetC < getCol()) {
                move = "LEFT";
            } else {//if(targetC > getCol())
                move = "RIGHT";
            }
        }
        else if (getOrientation().equals("South")) {
            if (targetR > getRow() && env.isCellFree(getRow() +1, getCol())) {
                move = "FWD"; //this is a good direction
            } else if (targetC < getCol()) {
                move = "RIGHT";
            } else {
                move = "LEFT";
            }
        }
        else if (getOrientation().equals("West")) {
            if (targetC  < getCol() && env.isCellFree(getRow() , getCol()-1)) {
                move = "FWD"; //this is a good direction
            } else if (targetR < getRow()) {
                move = "RIGHT";
            } else {
                move = "LEFT";
            }
        }
        else if (getOrientation().equals("East")) {
            if (targetC > getCol() && env.isCellFree(getRow() , getCol()+1)) {
                move = "FWD"; //this is a good direction
            } else if (targetR < getRow()) {
                move = "LEFT";
            } else {
                move = "RIGHT";
            }
        }
        return move;
    }
    

    private int abs(int x) {
        return x>=0?x:-x;
    }
    private void findTarget(Enviroment env) {
        int targetD=Integer.MAX_VALUE;
        for (int i = 0; i < env.rows; i++) {
                for (int j = 0; j < env.cols; j++) {
                    if (env.map[i][j]=='F' && abs(getRow()-i) + abs(getCol()-j) < targetD) {
                        targetR=i;
                        targetC=j;
                        targetD=abs(getRow()-i) + abs(getCol()-j);
                        hasTarget=true;
                    }
                }
            }
        System.out.println("$$$ my target is now the flag at "+targetR+","+targetC+" $$$");
    }
}
